package com.mumu.xiaodu

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.mumu.xiaodu.databinding.ActivityTvBrowserBinding

class TVBrowserActivity : FragmentActivity() {
    
    private lateinit var binding: ActivityTvBrowserBinding
    private lateinit var bookmarkAdapter: BookmarkAdapter
    private lateinit var bookmarkManager: BookmarkManager
    private lateinit var historyManager: HistoryManager
    private val memoryManager = MemoryManager.getInstance()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTvBrowserBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initManagers()
        initViews()
        loadBookmarks()
    }
    
    private fun initManagers() {
        // 初始化内存管理器 - 自用Demo最大权限配置
        memoryManager.initialize(this)
        
        bookmarkManager = BookmarkManager(this)
        historyManager = HistoryManager(this)
    }
    
    private fun initViews() {
        // 初始化书签网格 - 4列网格，简洁布局
        bookmarkAdapter = BookmarkAdapter(
            onBookmarkClick = { bookmark ->
                openWebsite(bookmark.url)
            },
            onAddBookmarkClick = {
                showBookmarkManager()
            }
        )
        val gridLayoutManager = GridLayoutManager(this, 4)
        binding.rvBookmarks.layoutManager = gridLayoutManager
        binding.rvBookmarks.adapter = bookmarkAdapter
        
        // 添加网格间距装饰器 - 确保书签之间有明显间距
        val spacingInPixels = resources.getDimensionPixelSize(R.dimen.grid_spacing)
        binding.rvBookmarks.addItemDecoration(
            GridSpacingItemDecoration(4, spacingInPixels, true)
        )
        
        // TV导航支持和滚动配置
        binding.rvBookmarks.setHasFixedSize(true)
        binding.rvBookmarks.isFocusable = true
        binding.rvBookmarks.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
        
        // 🔧 强制启用滚动功能
        binding.rvBookmarks.isNestedScrollingEnabled = true
        binding.rvBookmarks.isVerticalScrollBarEnabled = true
        binding.rvBookmarks.overScrollMode = View.OVER_SCROLL_ALWAYS
        binding.rvBookmarks.isScrollbarFadingEnabled = false
        
        // 🔧 确保GridLayoutManager支持垂直滚动
        gridLayoutManager.orientation = LinearLayoutManager.VERTICAL
        gridLayoutManager.reverseLayout = false
        
        // 搜索按钮点击事件
        binding.btnSearch.setOnClickListener {
            val query = binding.etSearchUrl.text.toString().trim()
            if (query.isNotEmpty()) {
                openWebsite(query)
            }
        }
        
        // 前进后退按钮
        binding.btnBack.setOnClickListener {
            showExitPrompt()
        }
        
        binding.btnForward.setOnClickListener {
            openLastVisitedSite()
        }
        
        // 底部导航
        binding.btnAiAssistant.setOnClickListener {
            openWebsite("https://www.doubao.com/chat/")
        }
        
        binding.btnLive.setOnClickListener {
            openWebsite("https://tv.cctv.cn/live/index.shtml")
        }
        
        binding.btnHome.setOnClickListener {
            Toast.makeText(this, "当前已在主页", Toast.LENGTH_SHORT).show()
        }
        
        // 长按主页按钮显示内存状态（自用Demo功能）
        binding.btnHome.setOnLongClickListener {
            showMemoryStats()
            true
        }
        
        binding.btnHistory.setOnClickListener {
            showHistory()
        }
        
        binding.btnBookmarks.setOnClickListener {
            showBookmarkManager()
        }
        
        // 设置默认焦点
        binding.etSearchUrl.requestFocus()
    }
    
    private fun loadBookmarks() {
        val bookmarks = bookmarkManager.getAllBookmarks()
        if (bookmarks.isEmpty()) {
            addDefaultBookmarks()
        } else {
            bookmarkAdapter.updateBookmarks(bookmarks)
        }
    }
    
    private fun addDefaultBookmarks() {
        val defaultBookmarks = listOf(
            Bookmark("百度搜索", "https://www.baidu.com", "search"),
            Bookmark("快客影院", "https://www.king0755.cn/", "video"),
            Bookmark("星空影院", "https://www.jutonghr.com/", "video"),
            Bookmark("抖音", "https://www.douyin.com/", "video"),
            Bookmark("免费影院", "http://v.szhmed.com/", "video"),
            Bookmark("爱奇艺", "https://www.iqiyi.com", "video"),
            Bookmark("腾讯视频", "https://film.qq.com", "video"),
            Bookmark("优酷", "https://www.youku.com", "video"),
            Bookmark("哔哩哔哩", "https://www.bilibili.com", "video")
        )
        
        defaultBookmarks.forEach { bookmark ->
            bookmarkManager.addBookmark(bookmark)
        }
        
        // 显示所有书签
        bookmarkAdapter.updateBookmarks(defaultBookmarks)
    }
    

    
    private fun openWebsite(url: String) {
        val intent = Intent(this, WebViewActivity::class.java)
        intent.putExtra("url", url)
        startActivity(intent)
    }
    
    private fun showExitPrompt() {
        Toast.makeText(this, "再按一次返回键退出应用", Toast.LENGTH_SHORT).show()
    }
    
    private fun openLastVisitedSite() {
        val lastSite = historyManager.getLastVisited()
        if (lastSite != null) {
            openWebsite(lastSite.url)
        } else {
            Toast.makeText(this, "暂无浏览记录", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun showHistory() {
        val intent = Intent(this, HistoryActivity::class.java)
        startActivity(intent)
    }
    
    private fun showBookmarkManager() {
        val intent = Intent(this, BookmarkManagerActivity::class.java)
        startActivity(intent)
    }
    

    
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                showExitPrompt()
                return true
            }
            KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> {
                return super.onKeyDown(keyCode, event)
            }
            KeyEvent.KEYCODE_DPAD_DOWN -> {
                // 如果当前焦点在搜索框，向下导航到书签区域
                if (binding.etSearchUrl.hasFocus()) {
                    binding.rvBookmarks.requestFocus()
                    binding.rvBookmarks.getChildAt(0)?.requestFocus()
                    return true
                }
                // 在书签区域内，允许正常滚动
                return false
            }
            KeyEvent.KEYCODE_DPAD_UP -> {
                // 如果在书签区域内但不是第一行，允许正常滚动
                if (binding.rvBookmarks.hasFocus()) {
                    val layoutManager = binding.rvBookmarks.layoutManager as? GridLayoutManager
                    val firstVisibleItem = layoutManager?.findFirstVisibleItemPosition() ?: 0
                    if (firstVisibleItem > 3) { // 不是第一行，允许向上滚动
                        return false
                    }
                    // 如果是第一行，向上导航到搜索框
                    binding.etSearchUrl.requestFocus()
                    return true
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }
    
    /**
     * 显示内存状态（自用Demo功能）
     */
    private fun showMemoryStats() {
        val stats = memoryManager.getMemoryStats()
        android.app.AlertDialog.Builder(this)
            .setTitle("📊 内存状态监控")
            .setMessage(stats)
            .setPositiveButton("强制清理内存") { _, _ ->
                memoryManager.forceMemoryCleanup()
                Toast.makeText(this, "内存清理完成", Toast.LENGTH_SHORT).show()
            }
            .setNeutralButton("关闭", null)
            .show()
    }
    
    override fun onDestroy() {
        // 清理内存管理器资源
        memoryManager.destroy()
        super.onDestroy()
    }
} 